#!/usr/bin/python3
# -*- coding:utf-8 -*-
"""
@author: henry_oulen
@file: json_tools.back.py
@time: 2023/8/28 9:27
@desc:
"""
import base64
import datetime
import hashlib
import json
import os
import queue
import random
import re
import shutil
import time
import tkinter
from concurrent.futures import ThreadPoolExecutor
from io import BytesIO
from tkinter import ANCHOR, END, SOLID
from tkinter.ttk import Label
from urllib.request import urlopen
import win32gui, win32con, win32api
import psutil
import requests
from PIL import Image

from json_tool.baidu_api import get_access_token
from json_tool.config_json_tool import app_id, api_key, secret_key_wx, secret_key_fy
from json_tool.icon import Icon
from json_tool.utils import day_laster, get_content
request_thread = None
import threading

# 创建一个队列用于线程间通信
result_queue = queue.Queue()

from sqlalchemy import create_engine, Column, Integer, String, Text
from sqlalchemy.orm import declarative_base
from sqlalchemy.orm import sessionmaker

# 创建基类
Base = declarative_base()


class System_info(Base):
    __tablename__ = 'system_info'
    id = Column(Integer, primary_key=True)
    name = Column(String(50))
    value = Column(Integer)


class Day_info(Base):
    __tablename__ = 'day_info'
    id = Column(Integer, primary_key=True)
    this_date = Column(String(50))
    key = Column(String(50))
    content = Column(Text)


# 连接到 SQLite 数据库
engine = create_engine('sqlite:///json_tool.db', echo=True)
Base.metadata.create_all(engine)

# 创建会话
Session = sessionmaker(bind=engine)
session = Session()


def handle_timestamp_formate(event):
    if time_stamp_input.get():
        need_time = time_stamp_input.get().strip()
        time_local = time.localtime(int(need_time))  # 转化成localtime
        time_format = time.strftime("%Y-%m-%d %H:%M:%S", time_local)
        last_print_text.delete('1.0', END)
        last_print_text.insert(END, "\n", "center")  # ADDED
        last_print_text.insert(END, "\n", "center")  # ADDED
        last_print_text.insert(END, "                   " + str(time_format), "center")
    else:
        now_time = int(time.time())
        time_local = time.localtime(now_time)  # 转化成localtime
        time_format = time.strftime("%Y-%m-%d %H:%M:%S", time_local)
        last_print_text.delete('1.0', END)
        last_print_text.insert(END, "\n", "center")  # ADDED
        last_print_text.insert(END, "\n", "center")  # ADDED
        last_print_text.insert(END, "                   " + str(time_format), "center")


def handle_formate_timestamp(event):
    if time_formate_input.get():
        formate_data = time_formate_input.get().strip()
        if len(formate_data) == 10:
            # 转换成时间数组
            time_array = time.strptime(formate_data, "%Y-%m-%d")
            # 转换成时间戳
            time_format = int(time.mktime(time_array))
            last_print_text.delete('1.0', END)
            last_print_text.insert(END, "\n", "center")  # ADDED
            last_print_text.insert(END, "\n", "center")  # ADDED
            last_print_text.insert(END, "                           " + str(time_format), "center")
        elif len(formate_data) == 19:  # "2023-03-21 15:11:25"
            time_array = time.strptime(formate_data, "%Y-%m-%d %H:%M:%S")
            # 转换成时间戳
            time_format = int(time.mktime(time_array))
            last_print_text.delete('1.0', END)
            last_print_text.insert(END, "\n", "center")  # ADDED
            last_print_text.insert(END, "\n", "center")  # ADDED
            last_print_text.insert(END, "                           " + str(time_format), "center")
        elif len(formate_data) == 16:  # "2023-04-01 14:00"
            time_array = time.strptime(formate_data, "%Y-%m-%d %H:%M")
            # 转换成时间戳
            time_format = int(time.mktime(time_array))
            last_print_text.delete('1.0', END)
            last_print_text.insert(END, "\n", "center")  # ADDED
            last_print_text.insert(END, "\n", "center")  # ADDED
            last_print_text.insert(END, "                           " + str(time_format), "center")
    else:
        now_time = int(time.time())
        last_print_text.delete('1.0', END)
        last_print_text.insert(END, "\n", "center")  # ADDED
        last_print_text.insert(END, "\n", "center")  # ADDED
        last_print_text.insert(END, "                           " + str(now_time), "center")  # ADDED


def handle_get_last_time(event):
    if can_time_stamp_input.get():
        need_time = can_time_stamp_input.get().strip()
        time_local = time.localtime(int(need_time))  # 转化成localtime
        time_format = time.strftime("%Y-%m-%d %H:%M", time_local)
        last_print_text.delete('1.0', END)
        last_print_text.insert(END, "\n", "center")  # ADDED
        last_print_text.insert(END, "\n", "center")  # ADDED
        last_print_text.insert(END, "           " + str(time_format), "center")
    else:
        now_time = int(time.time())
        time_local = time.localtime(now_time)  # 转化成localtime
        time_format = time.strftime("%Y-%m-%d %H:%M:%S", time_local)
        last_print_text.delete('1.0', END)
        last_print_text.insert(END, "\n", "center")  # ADDED
        last_print_text.insert(END, "\n", "center")  # ADDED
        last_print_text.insert(END, "           " + str(time_format), "center")


def handle_to_json(event):
    if sting_input.get():
        need_time = sting_input.get().strip()
        sting_output_button.delete('1.0', END)
        try:
            to_json = json.loads(need_time)
            last_send = json.dumps(to_json, ensure_ascii=False, indent=4, separators=(',', ':'))
            sting_output_button.insert(END, last_send, "center")  # ADDED
        except Exception as e:
            sting_output_button.delete('1.0', END)
            sting_output_button.insert(END, "字符串格式有误，请确认字符串使用的是为双引号\n", "center")  # ADDED
    else:
        sting_output_button.delete('1.0', END)
        sting_output_button.insert(END, "请在左边输入需要转化的字符串\n", "center")  # ADDED


def handle_auto_translate(is_en_to_zh=False):
    if sting_input.get():
        user_input = sting_input.get().strip()
        if user_input == "":
            sting_output_button.delete('1.0', END)
            sting_output_button.insert(END, "请在左边输入需要转化的字符串\n", "center")  # ADDED
        sting_output_button.delete('1.0', END)
        try:
            if not is_en_to_zh:
                from_lang = 'en'
                to_lang = 'zh'
            else:
                from_lang = 'zh'
                to_lang = 'en'
            # 你的百度翻译API应用ID和密钥
            # 生成随机数salt
            salt = str(random.randint(32768, 65536))
            # 拼接字符串1
            sign_string = app_id + user_input + salt + secret_key_fy

            # 对字符串1做MD5加密
            sign = hashlib.md5(sign_string.encode()).hexdigest()

            # 拼接完整的请求URL
            url = f'http://api.fanyi.baidu.com/api/trans/vip/translate?q={user_input}&from={from_lang}&to={to_lang}&appid={app_id}&salt={salt}&sign={sign}'

            # 发送GET请求
            response = requests.get(url)

            translated_text = "请稍后重试"
            # 解析响应数据
            if response.status_code == 200:
                result = response.json()
                translated_text = result['trans_result'][0]['dst']
                translated_text = translated_text.replace(" ", "_")
            sting_output_button.insert(END, translated_text, "center")  # ADDED
        except Exception as e:
            sting_output_button.delete('1.0', END)
            sting_output_button.insert(END, "API异常\n", "center")  # ADDED
    else:
        sting_output_button.delete('1.0', END)
        sting_output_button.insert(END, "请在左边输入需要转化的字符串\n", "center")  # ADDED


def handle_chat_message():
    chat_message = sting_input.get().strip()
    key = api_key.strip()
    sec_key = secret_key_wx.strip()
    if key and sec_key:
        if chat_message:
            if key and sec_key:
                url = "https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/completions_pro?access_token=" + get_access_token(
                    api_key, secret_key_wx)
                payload = json.dumps({
                    "messages": [
                        {
                            "role": "user",
                            "content": f"{chat_message}"
                        }
                    ]
                })
                headers = {
                    'Content-Type': 'application/json'
                }
                response = requests.request("POST", url, headers=headers, data=payload)
                response_message = response.json().get("result")
                sting_output_button.delete('1.0', END)
                sting_output_button.insert(END, response_message, "center")  # ADDED
                request_thread = None
        else:
            sting_output_button.delete('1.0', END)
            sting_output_button.insert(END, "请在左边输入想要查询的问题\n", "center")  # ADDED
    else:
        sting_output_button.delete('1.0', END)
        sting_output_button.insert(END, "请先配置api_key,secret_key\n", "center")  # ADDED


def start_request_baidu():
    global request_thread
    if request_thread is None or not request_thread.is_alive():
        download_thread = threading.Thread(target=handle_chat_message)
        download_thread.start()


def clean_input(event):
    sting_input.delete(0, END)


def listbox_copy(event):
    window.clipboard_clear()
    selected = last_print_text.get(ANCHOR)
    selected = selected.strip()
    window.clipboard_append(selected)


def copy_to_clipboard():
    """Copy current contents of text_entry to clipboard."""
    window.clipboard_clear()  # Optional.
    window.clipboard_append(last_print_text.get('1.0', END).rstrip().strip())


def copy_to_json_clipboard():
    """Copy current contents of text_entry to clipboard."""
    window.clipboard_clear()  # Optional.
    window.clipboard_append(sting_output_button.get('1.0', END).rstrip().strip())


def get_now_time():
    time_str = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f')  # 获取当前的时间并转化为字符串
    week_int = datetime.datetime.now().weekday()  # 获取当前的时间并转化为字符串
    date_dict = {
        0: "星期一",
        1: "星期二",
        2: "星期三",
        3: "星期四",
        4: "星期五",
        5: "星期六",
        6: "星期日",
    }
    week_str = date_dict.get(week_int)
    now_time_label.configure(text=time_str)  # 重新设置标签文本
    dat_num_label.configure(text=week_str)  # 重新设置标签文本
    window.after(100, get_now_time)  # 每隔1s调用函数 get_now_time 自身获取时间


def get_current_weather():
    code = "310000"
    key = "c7d042524a1431fb932ff9d29e34eab6"
    # 1.获取API
    url = f"https://restapi.amap.com/v3/weather/weatherInfo?city={code}&key={key}&output=JSON&extensions=base"
    # print(url)
    res = urlopen(url)
    data = json.loads(res.read())
    # province = data['lives'][0]['province']  # 省份
    city = data['lives'][0]['city']  # 城市
    weather = data['lives'][0]['weather']  # 天气情况
    temperature = data['lives'][0]['temperature']  # 温度
    winddirection = data['lives'][0]['winddirection']  # 风向
    windpower = data['lives'][0]['windpower']  # 风力 级
    humidity = data['lives'][0]['humidity']  # 空气湿度
    reporttime = data['lives'][0]['reporttime'][:16]  # 发布时间
    # msg = f"北京时间:{reporttime}          城市：{province}-{city}    \r\n天气:{weather}  温度:{temperature}°C  风向:{winddirection}  风力:{windpower}级  空气湿度:{humidity}%  "
    msg = f"城市:{city}  天气:{weather}\r\n温度:{temperature}°C  风向:{winddirection}\r\n风力:{windpower}级  空气湿度:{humidity}%"
    weather_stamp_show.configure(text=msg)  # 重新设置标签文本
    # 处理桌面壁纸
    # 查询开关状态
    switch_obj = session.query(System_info).filter_by(name="switch").first()
    if switch_obj.value == 1:
        # pass
        thread = BingUHD(set_desktop_picture)
        thread.start()
    window.after(1000 * 60 * 60 * 6, get_current_weather)  # 每隔1s调用函数 gettime 自身获取时间


# 定义一个函数，用于在后台线程中获取CPU和内存使用率
def get_resource_usage(queue):
    """
    Retrieves CPU and memory usage metrics and stores them in a queue.
    """
    while True:
        interval = 0.5
        cpu_percent = psutil.cpu_percent(interval=1)
        memory_percent = psutil.virtual_memory().percent
        # 获取网络IO统计信息
        net_io = psutil.net_io_counters(pernic=True)

        # 初始化上传和下载的字节数
        total_upload_before = 0
        total_download_before = 0

        # 遍历所有网络接口并累加上传和下载的字节数
        for interface in net_io:
            if "以太网" in interface or "Ethernet" in interface:
                total_upload_before += net_io[interface].bytes_sent
                total_download_before += net_io[interface].bytes_recv

        # 暂停一段时间
        time.sleep(interval)

        # 再次获取网络IO统计信息
        net_io = psutil.net_io_counters(pernic=True)

        # 初始化上传和下载的增量
        total_upload_after = 0
        total_download_after = 0

        # 遍历所有网络接口并累加上传和下载的增量
        for interface in net_io:
            if "以太网" in interface or "Ethernet" in interface:
                total_upload_after += net_io[interface].bytes_sent
                total_download_after += net_io[interface].bytes_recv

        # 计算总的上传和下载速度（单位：KB/s）
        total_upload_speed = (total_upload_after - total_upload_before) / 1024 / interval
        total_download_speed = (total_download_after - total_download_before) / 1024 / interval

        queue.put((cpu_percent, memory_percent, total_upload_speed, total_download_speed))
        time.sleep(1)


def handle_memory_cpu():
    """
    处理内存和CPU显示
    :return:
    """
    try:
        cpu_nums, memory_nums, total_upload_speed, total_download_speed = result_queue.get_nowait()
        cpu_color = "#58A2D5"
        memory_color = "#9AC733"
        up_color = "#FA9014"
        down_color = "#FA9014"
        if int(cpu_nums) > 80:
            cpu_color = "#CB1B04"
        if int(memory_nums) > 80:
            memory_color = "#CB1B04"
        if total_upload_speed >= 1024:
            total_upload_speed /= 1024
            upload_unit = "MB/s"
            up_color = "#CB1B04"
        else:
            upload_unit = "KB/s"

        if total_download_speed >= 1024:
            total_download_speed /= 1024
            download_unit = "MB/s"

            down_color = "#CB1B04"
        else:
            download_unit = "KB/s"

        show_upload_speed.configure(text=f"↑:{total_upload_speed:.2f}{upload_unit}", fg=up_color)
        show_download_speed.configure(text=f"↓:{total_download_speed:.2f}{download_unit}", fg=down_color)
        show_cpu_.configure(text=f"CPU:{cpu_nums}%", fg=cpu_color)  # 重新设置标签文本
        show_memory_label.configure(text=f"内存:{memory_nums}%", fg=memory_color)  # 重新设置标签文本

    except queue.Empty:
        pass
    window.after(1000, handle_memory_cpu)


def local_day_laster():
    send = day_laster()
    last_print_text_answer.delete('1.0', END)
    last_print_text_answer.insert(END, send, "center")  # ADDED


def set_desktop_picture():
    """
    设置桌面壁纸
    :return:
    """
    path = './BingUHD/'
    # name = 20240814+"3840x2160.jpg"
    today = datetime.datetime.now()
    yesterday = today - datetime.timedelta(days=1)
    file_name = path + str(yesterday.strftime("%Y%m%d")) + "3840x2160.jpg"
    current_dir = os.getcwd()
    relative_path = os.path.join(current_dir, file_name)
    if not os.path.exists(file_name):
        thread = BingUHD(set_desktop_picture)
        thread.start()
    if os.path.exists(file_name):
        k = win32api.RegOpenKeyEx(win32con.HKEY_CURRENT_USER, "Control Panel\\Desktop", 0, win32con.KEY_SET_VALUE)
        win32api.RegSetValueEx(k, "WallpaperStyle", 0, win32con.REG_SZ, "2")  # 2拉伸适应桌面，0桌面居中
        win32api.RegSetValueEx(k, "TileWallpaper", 0, win32con.REG_SZ, "0")
        win32gui.SystemParametersInfo(win32con.SPI_SETDESKWALLPAPER, relative_path, 1 + 2)


# 查询开关状态
switch_obj = session.query(System_info).filter_by(name="switch").first()
if not switch_obj:
    switch_obj = System_info(name="switch", value=0)
    session.add(switch_obj)
    session.commit()


# is_on = switch_obj.
def on_switch_change():
    """
    壁纸切换
    :return:
    """
    switch_obj = session.query(System_info).filter_by(name="switch").first()
    if switch_var.get():
        switch_obj.value = 1
        session.commit()
        set_desktop_picture()
    else:
        switch_obj.value = 0
        session.commit()


class NewsUpdaterThread(threading.Thread):
    def __init__(self, urls, callback):
        threading.Thread.__init__(self)
        self.urls = urls
        self.callback = callback
        self.headers = {
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.130 Safari/537.36"}

    def run(self):
        now = datetime.datetime.now()
        # 格式化为 "yyyyMMdd" 格式
        formatted_date = now.strftime('%Y%m%d')
        for url in self.urls:
            try:
                existing_record = session.query(Day_info).filter_by(this_date=formatted_date, key=url[1]).first()
                if not existing_record:
                    last_send = []
                    response = requests.get(url[0], headers=self.headers)
                    html = response.text
                    return_list = get_content(html, "news", url[1])
                    last_send = last_send + return_list
                    last_send.append("---------------------------")
                    last_content = "认认真真上班，这根本就不叫赚钱，那是用劳动换取报酬。"
                    _last_content = "人活半辈子才明白，真正高级的养生，是回家好好吃饭"
                    _last_content0 = "别沮丧，生活就像心电图，一帆风顺就证明你挂了！"
                    _last_content1 = "最后，祝愿天下所有摸鱼人，都能愉快的渡过每一天!"
                    _last_content2 = "关注我，这样每天我都能见到你了"
                    _last_content3 = "我是 【捣蛋小能手】 捣蛋的捣 & 捣蛋的蛋 ! "
                    _last_content4 = "email:henry_oulen@163.com"

                    last_send.append(last_content)
                    last_send.append(_last_content)
                    last_send.append(_last_content0)
                    last_send.append(_last_content1)
                    last_send.append(_last_content2)
                    last_send.append(_last_content3)
                    last_send.append(_last_content4)
                    #     # 如果没有找到记录，那么插入一条新记录
                    new_record = Day_info(this_date=formatted_date, key=url[1],
                                          content=json.dumps(last_send, ensure_ascii=False))
                    session.add(new_record)
                    session.commit()
                else:
                    last_send = session.query(Day_info).filter_by(this_date=formatted_date, key=url[1]).first().content
                    last_send = json.loads(last_send)
                    if not last_send:
                        response = requests.get(url[0], headers=self.headers)
                        html = response.text
                        return_list = get_content(html, "news", url[1])
                        last_send = last_send + return_list
                        last_send.append("---------------------------")
                        last_content = "认认真真上班，这根本就不叫赚钱，那是用劳动换取报酬。"
                        _last_content = "人活半辈子才明白，真正高级的养生，是回家好好吃饭"
                        _last_content0 = "别沮丧，生活就像心电图，一帆风顺就证明你挂了！"
                        _last_content1 = "最后，祝愿天下所有摸鱼人，都能愉快的渡过每一天!"
                        _last_content2 = "关注我，这样每天我都能见到你了"
                        _last_content3 = "我是 【捣蛋小能手】 捣蛋的捣 & 捣蛋的蛋 ! "
                        _last_content4 = "email:henry_oulen@163.com"
                        last_send.append(last_content)
                        last_send.append(_last_content)
                        last_send.append(_last_content0)
                        last_send.append(_last_content1)
                        last_send.append(_last_content2)
                        last_send.append(_last_content3)
                        last_send.append(_last_content4)
                send = ""
                for i in last_send:
                    send += i + "\r\n"
                self.callback(send)
            except requests.RequestException as e:
                print(f"Error fetching {url}: {e}")


# 示例的界面更新函数
def update_gui(news):
    # 实现更新界面的逻辑，例如更新文本框或标签
    last_print_text_answer.delete('1.0', END)
    last_print_text_answer.insert(END, news + "\n")


def local_get_today():
    urls = [['https://tophub.today/c/news', "today"]]
    thread = NewsUpdaterThread(urls, update_gui)
    thread.start()


def local_get_hot_news():
    urls = [['https://tophub.today/c/news', "hot"]]
    thread = NewsUpdaterThread(urls, update_gui)
    thread.start()


def can_time_stamp_show():
    show_string = "<-输入日期 xxxx-xx-xx xx:xx"
    if can_time_stamp_input.get():
        try:
            need_time = can_time_stamp_input.get().strip()
            if len(need_time) > 16:
                need_time = need_time[:16]
            # 将其转换为datetime对象，需要指定时间格式
            dt_obj = datetime.datetime.strptime(need_time, '%Y-%m-%d %H:%M')
            # 将datetime对象转换为时间戳（Unix时间戳）
            new_timestamp = int(dt_obj.timestamp())
            now_timestamp = int(time.time())
            # 将时间戳转换为datetime对象
            dt1 = datetime.datetime.fromtimestamp(new_timestamp)
            dt2 = datetime.datetime.fromtimestamp(now_timestamp)
            # 计算差值
            delta = dt1 - dt2
            # 获取相差的天数、小时数、分钟数和秒数
            days = delta.days
            hours, remainder = divmod(delta.seconds, 3600)
            minutes, seconds = divmod(remainder, 60)

            show_string = f"相差 {days} 天 {hours} 小时 {minutes} 分钟 {seconds} 秒"
        except Exception as e:
            show_string = "输入有误"
    else:
        need_time = "2025-01-28 12:00"
        last_period_date = "2024/04/25"
        cycle_length = 28
        # 将其转换为datetime对象，需要指定时间格式
        dt_obj = datetime.datetime.strptime(need_time, '%Y-%m-%d %H:%M')
        # 将datetime对象转换为时间戳（Unix时间戳）
        new_timestamp = int(dt_obj.timestamp())
        now_timestamp = int(time.time())
        # 将时间戳转换为datetime对象
        dt1 = datetime.datetime.fromtimestamp(new_timestamp)
        dt2 = datetime.datetime.fromtimestamp(now_timestamp)
        # 计算差值
        delta = dt1 - dt2
        # 获取相差的天数、小时数、分钟数和秒数
        days = delta.days
        hours, remainder = divmod(delta.seconds, 3600)
        minutes, seconds = divmod(remainder, 60)

        last_period_date = datetime.datetime.strptime(last_period_date, '%Y/%m/%d')
        current_date = datetime.datetime.now()

        # 计算已经过去的周期数
        elapsed_cycles = (current_date - last_period_date).days // cycle_length

        # 计算当前周期的天数
        days_into_current_cycle = (current_date - last_period_date).days % cycle_length

        # # 计算总周数和剩余天数
        total_weeks = elapsed_cycles * 4 + days_into_current_cycle // 7
        remaining_days = days_into_current_cycle % 7

        show_string = f"除夕:{days}天{hours}时{minutes}分{seconds}秒 {total_weeks}w+{remaining_days}d"
        # show_string = f"除夕:{days}天{hours}时{minutes}分{seconds}秒 "
    can_time_stamp_show_input.configure(text=show_string)  # 重新设置标签文本
    window.after(100, can_time_stamp_show)  # 每隔1s调用函数 get_now_time 自身获取时间


class BingUHD(threading.Thread):

    def __init__(self, callback):
        threading.Thread.__init__(self)
        # 默认bing图片查询地址
        self.url = 'https://cn.bing.com/HPImageArchive.aspx?format=js&idx=0&n=1&mkt=ZH-CN'
        self.path = './BingUHD/'
        self.headers = {
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) '
                          'Chrome/80.0.3987.132 Safari/537.36'
        }
        self.resolution = 'UHD'
        self.callback = callback

    # 取得图片相关信息
    def get_img_info(self):
        try:
            # 获取图片信息
            result = requests.get(self.url, headers=self.headers).json()
            # 提取图片地址
            raw_img_url = 'https://cn.bing.com' + result['images'][0]['url']
            # 得到默认图片链接
            normal_img_url = raw_img_url[0:raw_img_url.find(".jpg") + 4]
            # 得到UHD图片链接替换默认的 1080 图片为UHD图片链接
            uhd_img_url = normal_img_url.replace("1920x1080", self.resolution)
            # 提取中文标题和版权信息
            date = result["images"][0]["startdate"]
            title = result["images"][0]["title"]
            copy_right = result["images"][0]["copyright"]
            return normal_img_url, uhd_img_url, date, title, copy_right

        except Exception as e:
            print('错误: 无法获取到图片地址，请检查网络连接' + '\n')

    def img_download(self, url, file_name):
        try:
            response = requests.get(url, stream=True)
            if response.status_code == 200:
                with open(file_name, 'wb') as f:
                    response.raw.decode_content = True
                    shutil.copyfileobj(response.raw, f)
                print(file_name + "图片下载成功")
            else:
                print(file_name + "无法下载图片")
        except Exception as e:
            print('错误: 无法下载图片，请检查网络连接' + '\n')

    # 得到今日图片信息并清洗
    def get_today_img_download(self, file_name):
        try:
            info = self.get_img_info()
            normal_url = info[0]
            uhd_url = info[1]
            # 图片分辨率文字
            # normal = normal_url[(normal_url.rfind("_") + 1): -4]
            # uhd = uhd_url[(uhd_url.rfind("_") + 1): -4]

            # 图片分辨率文字
            normal = self.get_pic_size()[0]
            uhd = self.get_pic_size()[1]
            # self.img_download(normal_url, file_name + normal + '.jpg')
            self.img_download(uhd_url, file_name + uhd + '.jpg')
        except Exception as e:
            print('错误: 无法获取到图片信息，请检查网络连接' + '\n')

    # 取得文件名称
    def get_file_name(self):
        try:
            info = self.get_img_info()
            # 定义文件夹
            # file_path = self.path + info[2][0:4] + '-' + info[2][4:6] + '/'
            file_path = self.path + '/'
            # 判断文件夹是否存在
            if not os.path.exists(file_path):
                os.makedirs(file_path)
            # 定义文件名
            copy_right = info[4]
            copy_right = copy_right[0:copy_right.find(' ')]
            # 绝对路径
            # name = info[2] + '.' + info[3] + '.' + copy_right + '.'
            name = info[2]
            full_name = file_path + name
            return full_name
        except Exception as e:
            print('错误: 无法获取到图片信息，请检查网络连接' + '\n')

    # 取得图片的尺寸
    def get_pic_size(self):
        """
        获取远程图片的尺寸
        :return:
        """
        size_list = []
        url = [self.get_img_info()[0], self.get_img_info()[1]]
        for u in url:
            r = requests.get(u)
            img = Image.open(BytesIO(r.content))
            pic_size = str(img.width) + 'x' + str(img.height)
            size_list.append(pic_size)
        return size_list

    # 取得今日美图文字
    def get_description(self):
        url = 'https://www.bing.com/?mkt=zh-CN'
        rsp = requests.get(url)
        result = re.search(r'({"Description":")(.*?)(","Image")', rsp.text).group(2)
        return result

    def run(self):
        # bing = BingUHD()
        # path = './BingUHD/'
        # name = 20240814+"3840x2160.jpg"
        today = datetime.datetime.now()
        yesterday = today - datetime.timedelta(days=1)
        file_name = self.path + str(yesterday.strftime("%Y%m%d")) + "3840x2160.jpg"
        current_dir = os.getcwd()
        # relative_path = os.path.join(current_dir, file_name)
        if not os.path.exists(file_name):
            down_file_name = self.get_file_name()
            self.get_today_img_download(down_file_name)
        switch_obj = session.query(System_info).filter_by(name="switch").first()
        if switch_obj.value == 1:
            time.sleep(10)
            self.callback()


window = tkinter.Tk()

with open('tmp.ico', 'wb') as tmp:
    tmp.write(base64.b64decode(Icon().img))
window.iconbitmap('tmp.ico')
os.remove('tmp.ico')

width = window.winfo_screenwidth()
window.title('小工具 @author  >> henry.oulen@gmail.com   date:2024/08/15 v_0.0.1')

# 获取屏幕尺寸计算参数，使窗口显示再屏幕中央
screen_width = window.winfo_screenwidth()
screen_height = window.winfo_screenheight()
_width = 1920
_height = 1080
window_size = f'{_width}x{_height}+{round((screen_width - width) / 2)}+{round((screen_height - _height) / 2)}'  # round去掉小数

window.wm_state("zoomed")  # 设置打开的窗口最大化
window.config(bg="#1E1F22")
dat_num_label = tkinter.Label(window, text='', fg="#a9b7c6", font="等线 20 bold", bg="#1E1F22")
dat_num_label.place(relx=0.3, rely=0.02, relwidth=0.05, relheight=0.05)

# 当前时间
# now_time_label = tkinter.Label(window, text='', fg='#a9b7c6', font="等线 20 bold", bg="#5891E6")
now_time_label = tkinter.Label(window, text='', fg='#a9b7c6', font="等线 20 bold", bg="#1E1F22")
now_time_label.place(relx=0.35, rely=0.02, relwidth=0.2, relheight=0.05)
get_now_time()

# 自定义倒计时间
can_time_stamp_input = tkinter.Entry(window, font="等线 16 bold", background="#1E1F22", foreground="#a9b7c6",
                                     borderwidth=1,
                                     highlightthickness=1, relief=SOLID, highlightbackground="#a9b7c6")
can_time_stamp_input.place(relx=0.6, rely=0.02, relwidth=0.15, relheight=0.05)
# 当前时间

# can_time_stamp_show_input = tkinter.Label(window, text='', fg='#a9b7c6', font="等线 20 bold", bg="#5891E6")
# can_time_stamp_show_input = tkinter.Label(window, text='', fg='#a9b7c6', font="等线 20 bold", bg="#5891E6",fg="#5891E6")
can_time_stamp_show_input = tkinter.Label(window, text='', font="等线 19 bold", background="#1E1F22",
                                          fg="#78A817", )
can_time_stamp_show_input.place(relx=0.75, rely=0.02, relwidth=0.2, relheight=0.05)
can_time_stamp_show()

# 天气
# weather_stamp_show = tkinter.Label(window, text='天气', font="等线 11 bold", fg="#a9b7c6", bg="#5891E6")
# weather_stamp_show = tkinter.Label(window, text='天气', font="等线 11 bold", fg="#5891E6", bg="#a9b7c6")
weather_stamp_show = tkinter.Label(window, text='天气', font="等线 11 bold", background="#1E1F22",
                                   fg="#78A817", )
weather_stamp_show.place(relx=0.02, rely=0.01, relwidth=0.15, relheight=0.1)
get_current_weather()

time_stamp_show = Label(window, text='时间戳', font="等线 16 bold", background="#1E1F22", foreground="#a9b7c6")
time_stamp_show.place(relx=0.05, rely=0.1, relwidth=0.12, relheight=0.07, )
time_stamp_input = tkinter.Entry(window, font="等线 16 bold", background="#1E1F22", foreground="#a9b7c6", borderwidth=1,
                                 highlightthickness=1, highlightbackground="#a9b7c6", relief=SOLID, )
time_stamp_input.place(relx=0.05, rely=0.15, relwidth=0.12, relheight=0.05)

time_formate_show = Label(window, text='时间格式', font="等线 16 bold", background="#1E1F22", foreground="#a9b7c6")
time_formate_show.place(relx=0.17, rely=0.1, relwidth=0.12, relheight=0.07, )
time_formate_input = tkinter.Entry(window, font="等线 16 bold", justify="center", background="#1E1F22",
                                   foreground="#a9b7c6", borderwidth=1,
                                   highlightthickness=1, highlightbackground="#a9b7c6", relief=SOLID, )
time_formate_input.place(relx=0.17, rely=0.15, relwidth=0.12, relheight=0.05)

timestamp_to_formate = tkinter.Button(window, text="时间戳-->格式化", command="handle_timestamp_formate",
                                      activebackground="#0f73ef", borderwidth=1, highlightthickness=1, relief=SOLID,
                                      highlightbackground="#a9b7c6",
                                      font="等线 16 bold", background="#1E1F22", foreground="#a9b7c6")
timestamp_to_formate.bind("<Button-1>", handle_timestamp_formate)
timestamp_to_formate.place(relx=0.05, rely=0.2, relwidth=0.12, relheight=0.05)

formate_to_timestamp = tkinter.Button(window, text="时间格式-->时间戳", command="handle_formate_timestamp",
                                      activebackground="#0f73ef", borderwidth=1, highlightthickness=1, relief=SOLID,
                                      font="等线 16 bold", background="#1E1F22", foreground="#a9b7c6")
formate_to_timestamp.bind("<Button-1>", handle_formate_timestamp)
formate_to_timestamp.place(relx=0.17, rely=0.2, relwidth=0.12, relheight=0.05)

last_print_text = tkinter.Text(window, width=40, height=10, border=4, relief=SOLID, font="等线 16 bold", bg="#1E1F22",
                               fg="#99C794", borderwidth=1, highlightthickness=1, highlightbackground="#a9b7c6",
                               highlightcolor="#a9b7c6")
last_print_text.place(relx=0.05, rely=0.25, relwidth=0.24, relheight=0.1)

clp_text = tkinter.Button(window, text="复制到粘贴板",
                          command=copy_to_clipboard, activebackground="#0f73ef", font="等线 16 bold",
                          background="#1E1F22", foreground="#a9b7c6")
clp_text.place(relx=0.05, rely=0.35, relwidth=0.24, relheight=0.05)

# 定义消息对话框
last_button = tkinter.Button(window, padx=5, activebackground="#0f73ef", text="节日倒数", command=local_day_laster,
                             font="等线 16 bold", bg="#1E1F22", fg="#a9b7c6", borderwidth=1, highlightthickness=1,
                             relief=SOLID, )
last_button.pack()
last_button.place(relx=0.05, rely=0.42, relwidth=0.05, relheight=0.05)

get_hot_news_button = tkinter.Button(window, padx=5, activebackground="#0f73ef", text="今日热榜",
                                     command=local_get_hot_news, borderwidth=1, highlightthickness=1, relief=SOLID,
                                     font="等线 16 bold", bg="#1E1F22", fg="#a9b7c6", )
get_hot_news_button.pack()
get_hot_news_button.place(relx=0.145, rely=0.42, relwidth=0.05, relheight=0.05)

get_today_button = tkinter.Button(window, padx=5, activebackground="#0f73ef", text="历史今天", command=local_get_today,
                                  font="等线 16 bold", bg="#1E1F22", fg="#a9b7c6", borderwidth=1, highlightthickness=1,
                                  relief=SOLID, )
get_today_button.pack()
get_today_button.place(relx=0.24, rely=0.42, relwidth=0.05, relheight=0.05)

last_print_text_answer = tkinter.Text(window, width=40, height=10, border=4, relief=SOLID, font="等线 13 bold",
                                      bg="#1E1F22", fg="#99C794", borderwidth=1, highlightthickness=1,
                                      highlightbackground="#a9b7c6",
                                      highlightcolor="#a9b7c6")
last_print_text_answer.place(relx=0.05, rely=0.50, relwidth=0.24, relheight=0.45)

# 右边
sting_input = tkinter.Entry(window, font="等线 16 bold", bg="#1E1F22",
                            fg="#a9b7c6", borderwidth=1, highlightthickness=1, highlightbackground="#a9b7c6",
                            highlightcolor="#a9b7c6", relief=SOLID, )
sting_input.place(relx=0.3, rely=0.1, relwidth=0.2, relheight=0.05)

sting_input_button = tkinter.Button(window, text="Json格式化", activebackground="#0f73ef", font="等线 16 bold",
                                    bg="#1E1F22", fg="#a9b7c6")
sting_input_button.bind("<Button-1>", handle_to_json)
sting_input_button.place(relx=0.5, rely=0.1, relwidth=0.055, relheight=0.05)

sting_auto_trans_en_button = tkinter.Button(window, text="中-->英", activebackground="#0f73ef", font="等线 16 bold",
                                            bg="#1E1F22", fg="#a9b7c6")
# sting_auto_trans_en_button.bind("<Button-1>", handle_auto_translate)
sting_auto_trans_en_button.bind("<Button-1>", lambda event, text=True: handle_auto_translate(text))
sting_auto_trans_en_button.place(relx=0.555, rely=0.1, relwidth=0.05, relheight=0.05)
sting_auto_trans_cn_button = tkinter.Button(window, text="英-->中", activebackground="#0f73ef", font="等线 16 bold",
                                            bg="#1E1F22", fg="#a9b7c6")
# sting_auto_trans_cn_button.bind("<Button-1>", handle_auto_translate)
sting_auto_trans_cn_button.bind("<Button-1>", lambda event, text=False: handle_auto_translate(text))
sting_auto_trans_cn_button.place(relx=0.605, rely=0.1, relwidth=0.05, relheight=0.05)

# baidu_btn_button = tkinter.Button(window, text="文心一言", command=start_request_baidu,
#                                   activebackground="#0f73ef",
#                                   font="等线 16 bold")
# baidu_btn_button.place(relx=0.65, rely=0.1, relwidth=0.1, relheight=0.05)

sting_clean_button = tkinter.Button(window, text="清空", command="handle_formate_timestamp",
                                    activebackground="#0f73ef",
                                    font="等线 16 bold", bg="#1E1F22", fg="#a9b7c6")
sting_clean_button.bind("<Button-1>", clean_input)
sting_clean_button.place(relx=0.655, rely=0.1, relwidth=0.0375, relheight=0.05)

clp_json = tkinter.Button(window, text="复制",
                          command=copy_to_json_clipboard, activebackground="#0f73ef", font="等线 16 bold", bg="#1E1F22",
                          fg="#a9b7c6")
clp_json.place(relx=0.6925, rely=0.1, relwidth=0.0375, relheight=0.05)

show_upload_speed = tkinter.Label(window, text='', font="等线 14 bold", bg="#1E1F22", fg="#a9b7c6", borderwidth=1,
                                  highlightthickness=1, relief=SOLID, highlightbackground="#a9b7c6")
show_upload_speed.place(relx=0.73, rely=0.1, relwidth=0.06, relheight=0.05)

show_download_speed = tkinter.Label(window, text='', font="等线 14 bold", bg="#1E1F22", fg="#a9b7c6", borderwidth=1,
                                    highlightthickness=1, relief=SOLID, highlightbackground="#a9b7c6")
show_download_speed.place(relx=0.79, rely=0.1, relwidth=0.06, relheight=0.05)

show_cpu_ = tkinter.Label(window, text='', font="等线 14 bold", bg="#1E1F22", fg="#a9b7c6", borderwidth=1,
                          highlightthickness=1, relief=SOLID, highlightbackground="#a9b7c6")
show_cpu_.place(relx=0.85, rely=0.1, relwidth=0.05, relheight=0.05)

show_memory_label = tkinter.Label(window, text='', font="等线 14 bold", bg="#1E1F22", fg="#a9b7c6", borderwidth=1,
                                  highlightthickness=1, relief=SOLID, highlightbackground="#a9b7c6")
show_memory_label.place(relx=0.9, rely=0.1, relwidth=0.05, relheight=0.05)
# 创建一个线程池执行器
executor = ThreadPoolExecutor(max_workers=1)

resource_thread = threading.Thread(target=get_resource_usage, args=(result_queue,))
resource_thread.daemon = True  # Daemonize thread so it will be automatically killed when main program exits
resource_thread.start()
# 在主循环中开始更新过程
handle_memory_cpu()
sting_output_button = tkinter.Text(window, width=40, height=10, border=4, relief=SOLID, font="等线 16 bold",
                                   bg="#1E1F22", fg="#99C794", borderwidth=1, highlightthickness=1,
                                   highlightbackground="#a9b7c6")
sting_output_button.place(relx=0.3, rely=0.15, relwidth=0.65, relheight=0.8)

# 定义消息对话框
desktop_picture_button = tkinter.Button(window, padx=5, activebackground="#0f73ef", text="Bing壁纸",
                                        command=set_desktop_picture,
                                        font="等线 16 bold", bg="#1E1F22", fg="#78A817", borderwidth=1,
                                        highlightthickness=1,
                                        relief=SOLID, )
desktop_picture_button.pack()
desktop_picture_button.place(relx=0.9, rely=0.95, relwidth=0.05, relheight=0.03)
switch_var = tkinter.BooleanVar(value=True if switch_obj.value == 1 else False)
switch = tkinter.Checkbutton(window, text="On/Off", command=on_switch_change, font="等线 14 bold", bg="#1E1F22",
                             fg="#78A817", borderwidth=1, variable=switch_var,
                             highlightthickness=1,
                             relief=SOLID, )
switch.pack()
switch.place(relx=0.95, rely=0.95, relwidth=0.05, relheight=0.03)

# hand_today_json()

print(f"Successfully start run json tools {datetime.datetime.now()}")

# 我想要创建一个sqlite数据库，用来记录json格式化后的内容


window.mainloop()
